﻿//----------------------------------------------
// 将JSON数据，回传到页面,依赖于Jquery.json插件
// Version :V 0.1.0
// 表单操作类库
// 1、将JSON数据影射到Form里
// 2、将From的数据转换成JSON数据格式
// 3、URLEncode
// 4、数据保存操作
// 5、数据修改操作
// ----------------------------------------------------------
// 6、数据删除操作
// 7、数据查询
// ----------------------------------------------------------

(function ($) {
    $.JSONToForm = function (jsonString) {
        var json = jsonString;
        ///用於轉換日期格式
        json = json.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
        var o = $.evalJSON(json);
        $.each(o, function (property, value) {
            //try {
            value = value + "";
            // find the control and set value
            if (property != "") {
                var control = $("[name='" + property + "']");
                var strValue = value.replace(/@1@1@1/g, "'");
                strValue = strValue.replace(/@2@2@2/g, '"');
                strValue = strValue.replace(/@@@@/g, "\n");
                control.val(strValue);
                try {
                    $('#' + property).combobox('setValue', strValue);
                } catch (Error) { }
            }
            //  };
        });
    };
})(jQuery);

(function($) {
    $.fn.JSONToForm = function(jsonString) {
        var json = jsonString;
        ///用於轉換日期格式
        json = json.replace(new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\"', 'g'), "$1new Date($2)");
        var o = $.evalJSON(json);
        var controls = $(this).find('input, select, textarea, label');
        $.each(o, function(property, value) {
            //try {
            value = value + "";
            // find the control and set value
            if (property != "") {
                controls.each(function() {
                    if ($(this).attr("name") == property) {
                        //var c = this.find("[name='" + property + "']");
                        var strValue = value.replace(/@1@1@1/g, "'");
                            strValue = strValue.replace(/@2@2@2/g,'"');
                            strValue = strValue.replace(/@@@@/g,"\n");
                            if($(this)[0].tagName.toUpperCase()=='LABEL')
                            {
                                $(this).html(strValue);
                            }
                            else{
                        $(this).val(strValue);
                        try {
                            $('#' + property).combobox('setValue', value);
                        } catch (Error) { }
                        }
                    }
                });
            }
            //  };
        });
    };
})(jQuery);


///克隆对象
(function ($) {
    $.fn.Clone = function (o1, o2) {
        $.each(o1, function (property, value) {
            if (property != "") {
                eval("o2." + property + "='" + value + "'");
            }
        });
    }; 
})(jQuery);


///清理对应该控件
(function($) {
    $.fn.clear = function() {
        var controls = $(this).find('input, select, textarea');
        controls.each(function() {
            $(this).val('');
        });
    }
})(jQuery);

function repalceChars(value) {
    if (value.toString().indexOf("@1@1@1", 0) > 0) {
        value = value.toString().replace("@1@1@1", "'");
        return repalceChar(value);
    }
    else {
        return value;
    }
}

function repalceChar(value) {
    if (value.toString().indexOf("@@@@", 0) > 0) {
        value = value.toString().replace("@@@@", "\n");
        return repalceChar(value);
    }
    else {
        return value;
    }
}

//$.fn.List = function(o) {
//    alert("test" + o);
//    var defaults = {
//        ipt: this,
//        evt: "click"
//    };
//    if (o) {
//        $.extend(defaults, o);
//    }

//}
//var select;
//var items;

(function($) {
    $.fn.com = function(_5a) {
        _5a = _5a || {};
       var  select = this;
        $.get(_5a.url, function(data, textStatus) {
            //alert(data);
            var list;
            list = eval('(' + data + ')');
            for (var o in list) {
                var v = eval("list[o]." + _5a.valueField);
                var t = eval("list[o]." + _5a.textField);
                select[0].options.add(new Option( t,v));
            }
        });
    };
})(jQuery);


(function($) {
    $.fn.com = function(_5a) {
        _5a = _5a || {};
       var  select = this;
        $.get(_5a.url, function(data, textStatus) {
            //alert(data);
            var list;
            list = eval('(' + data + ')');
            for (var o in list) {
                var v = eval("list[o]." + _5a.valueField);
                var t = eval("list[o]." + _5a.textField);
                select[0].options.add(new Option( t,v));
            }
        });
    };
})(jQuery);


(function($) {
$.fn.comBind = function(list, v, t) {

        var select = this;
        var obj = null;
        if(typeof(list)=="String")
        {
            obj = eval(list);
        }
        else{
            obj = list;
        }
        for (var o in list) {
            var v1 = eval("list[o]." + v);
            var t1 = eval("list[o]." + t);
            select[0].options.add(new Option(t1, v1));
        }
    };
})(jQuery);


//
(function($) {
    $.encodeURI = function(zh) {
        if (window.RegExp && window.encodeURIComponent) {
            return encodeURIComponent(zh);
        }
        return zh;
    };
})(jQuery);


// 将Form元素对应成对象
$.fn.extractObject = function() {
    var accum = {};
    function add(accum, namev, value) {
        if (namev.length == 1) {
            if (namev[0] != "") {
                accum[namev[0]] = $.encodeURI(value);
            }
        }
        else {
            if (accum[namev[0]] == null)
                accum[namev[0]] = {};
            add(accum[namev[0]], namev.slice(1), $.encodeURI(value));
        }
    };

    this.find('input, textarea, select').each(function() {
        add(accum, $(this).attr('name').split('.'),$.trim($(this).val()));
    });
    return accum;
};

function gettrinput(id, index) {
    var accum = {};
    function add(accum, namev, value) {
        if (namev.length == 1) {
            if (namev[0] != "") {
                accum[namev[0]] = $.encodeURI(value);
            }
        }
        else {
            if (accum[namev[0]] == null)
                accum[namev[0]] = {};
            add(accum[namev[0]], namev.slice(1), $.encodeURI(value));
        }
    };
    $("#" + id + " tr:not(:first)").each(function() {
        //abc = parseFloat(abc).add(parseFloat($("td:nth-child(" + index + ") input", this).val()));
        try {
            var name = $("td:nth-child(" + index + ") input, textarea, select", this).attr('name');
            add(accum, name.split('.'), $("td:nth-child(" + index + ") input", this).val());
        } catch (Error) { }
    });
    return accum;
}

function settrinput(id, index, arr) {
    $("#" + id + " tr:not(:first)").each(function() {
        try {
            var name = $("td:nth-child(" + index + ") input, textarea, select", this).attr('name');
            $("td:nth-child(" + index + ") input", this).val(eval("arr."+name));
        } catch (Error) { }
    });
}

//加法函数，用来得到精确的加法结果 
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。 
//调用：accAdd(arg1,arg2) 
//返回值：arg1加上arg2的精确结果 
function accAdd(arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
}
//给Number类型增加一个add方法，调用起来更加方便。 
Number.prototype.add = function(arg) {
    return accAdd(arg, this);
}

function cal(id, index) {
    var total=0;
    var t = parseFloat($("#Total" + index).val());
    var str;
    $("#" + id + " tr:not(:first)").each(function() {
        try {
            //var name = $("td:nth-child(" + index + ") input, textarea, select", this).attr('name');
            //$("td:nth-child(" + index + ") input", this).val("1");
            var v = $("td:nth-child(" + index + ") input", this).val();
            str = str + v + ":";
            if (v === "" || v === undefined) {
                total = total.add(0);
            }
            else {
                var n = parseFloat(v);
                total = total.add(isNaN(n) ? 0 : n);
            }
        } catch (Error) { }
    });
    $("#Total" + index).val(total);
    //alert(str);
    
}
//function setValue(n, input, arr) {
//    var filter = $.grep(arr, function(value) {
//        return value.name == v;
//    });
//    if (filter.length > 0) {
//        input.valueOf(filter[0].name);
//    }
//} 
/// ------------------------------------------
/// 设置输入控件为只读
/// ------------------------------------------
$.fn.setInputReadOnly = function(bl) {
    this.find('input, textarea, select').each(function() {
    $(this)[0].readOnly = bl;
       // alert($(this)[0].name);
    });
}

/// ------------------------------------------
/// 设置输入控件数字控件
/// ------------------------------------------
$.fn.setInputNumber = function() {
    this.attr("ClassName", "easyui-numberbox");
}


///------------------------------------------------------------
/// 用于通用的数据保存操作
///------------------------------------------------------------
$.fn.SaveData = function (url, entity, mydata) {
    var strUrl = url + "?entity=" + entity + "&json=" + mydata;
    alert(strUrl);
    $.get(strUrl, function (data, textStatus) {
        if(data == "1") {
            alert("數據保存成功");
        }
        else{
            alert("數據保存失败");
        }
    });
};

///----------------------------------------------------------
/// 
///----------------------------------------------------------
$.fn.SaveData1 = function(url, entity, mydata, fn) {
    var strUrl = url + "?entity=" + entity + "&json=" + mydata;
    $.get(strUrl, function(data, textStatus) {
        //alert(data);
        if (data == "1") {
            $.messager.alert('提示', '數據保存成功!', 'info');
            if (typeof (fn) == "function") {
                fn();
            }
        }
        else {
            $.messager.alert('提示', data, 'info');
        }
    });
};

$.fn.SaveDataProject = function(url, entity, mydata) {
    var strUrl = url + "?entity=" + entity + "&json=" + mydata;
    $.get(strUrl, function(data, textStatus) {
        //alert(data);
        if (data == "1") {
            $.messager.alert('提示', '數據保存成功!', 'info');
            $('#w').window('hide');

        }
        else {
            $.messager.alert('提示', data, 'info');
        }
    });
};

$.fn.DeleteData = function(url, entity, mydata) {
var strUrl = url + "?entity=" + entity + "&json=" + mydata + "&action=delete";
    $.get(strUrl, function(data, textStatus) {
        //alert(data);
        if (data == "1") {
            $.messager.alert('提示', '數據刪除成功!', 'info');
        }
        else {
            $.messager.alert('提示', data, 'info');
        }
    });
};

var intervalID = 0;
function f_start() {
    intervalID = window.setInterval("logout()", 2000);
}

$.fn.logon = function(u, p) {
    window.clearInterval(intervalID); 
    var url = "AjaxData/logon.aspx?loginname=" + u + "&loginpass=" + p + "&n=" + Math.random();
    $.get(url, function(data, textStatus) {
        if (data == "1") {
            window.location = "paltform.aspx"
        }
        else {
            $.messager.alert('提示', '用戶不存在或者密碼錯誤，請重試!', 'info');
        }
    });
};


///----------------------------------------------------
///编辑
///----------------------------------------------------
function Edit(w, t) {
    var w1="w";
    if (typeof (w) != undefined) {
        w1 = w;
    }
    var t1 = "tt";
    if (typeof (t) != undefined) {
        t1 = t;
    }
    open1();
    var selected = $('#'+t1).datagrid('getSelected');
    if (selected != null) {
        $.JSONToForm($.toJSON(selected));
    }
    //alert(selected.MenuID + ":" + selected.ParentID);
}

///-----------------------------------------------------
///
///-----------------------------------------------------
function Delete(w,t,keyword) {
    var ids = [];
    var rows = $('#tt').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(eval('rows[i].MenuID'));
    }
    var s = ids.join(',');
    var url = "../AjaxData/SaveData.aspx";
    var entity = "E_Menu";
    $('#w').DeleteData(url, entity, s);

}

function ReloadData() {
    $('#tt').datagrid({
        url: '../AjaxData/JSONList.aspx?n=' + Math.random()
    });
}

//------------------------------------------------------
//打开默认窗口
//------------------------------------------------------
function open1() {
    if (typeof (parent.myEdit) == "function") {
        parent.myEdit('HtmlWindows/Edit.aspx',"Post","0");
    }
    else {
        open('w');
    }
}

//-------------------------------------------------------
// 打开编辑窗口
//-------------------------------------------------------
function open(w) {
    $('#' + w).window('open');
    //清空表单
    $('#ff').form('clear');
}

function open(w) {
    $('#' + w).window('open');
    //清空表单
    $('#ff').form('clear');
}


//-------------------------------------------------------
// 关闭编辑窗口
//-------------------------------------------------------
function close(w) {
    $('#' + w).window('close');
}

//var _mytest;
//function mytest() {
//    var url = "../AjaxData/JSONList.aspx?n=" + Math.random();
//    $.get(url, function(data, textStatus) {
//        _mytest = eval(data);
//        alert(_mytest.toString());
//        //        if (data == "1") {
//        //            window.location = "paltform.aspx"
//        //        }
//        //        else {
//        //            $.messager.alert('提示', '用戶不存在或者密碼錯誤，請重試!', 'info');
//        //        }
//    });
//}
///

///
/// 用於獲取當前用戶信息
///
var user;
function InitUser() {

        $.get("../AjaxData/GetUserInfo.aspx", function(data, textStatus) {
            //alert(data);
            user = eval('('+data+')');
        });
}

function out() {

    $.get("../AjaxData/GetUserInfo.aspx", function(data, textStatus) {
        //alert(data);
        user = eval('(' + data + ')');
    });
}

function ChangePassword(password) {
    $.get("/AjaxData/changepassword.aspx?password=" + password, function(data, textStatus) {
        if (data == "0") {
            $.messager.alert('提示', '密碼己修改成功!', 'info');
            close('w');
        }
        else {
        
        }
    });
}

function logout() {
    $.get("logout.aspx", function(data, status) { var i = 0;  });
    //setTimeout(logout, 1000);
}


function ViewDoc(file) {
    if (file == "") {
        $.messager.alert('提示', '沒有文檔!', 'info');
        return;
    }
    parent.viewdoc(getUrl() + file);
}


function vd(i) {
    var file = $('#DocFile' + i).val();
    ViewDoc(file);
}

function getUrl() {
    return "http://"+document.location.host;
}

function getPar(source, name) {
    var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
    if (reg.test(source)) return RegExp.$2; return "";
}

function getPar1(name) {
    var _url = "http://"+document.location;
    return getPar(_url, name);
}

//var dataQuery = function() {
//dataQuery..Condtion = "";
//}
//var Q = new dataQuery();
//Q.c
function Encrypt(str, pwd) {
    if (str == "") return "";
    str = escape(str);
    if (!pwd || pwd == "") { var pwd = "1234"; }
    pwd = escape(pwd);
    if (pwd == null || pwd.length <= 0) {
        alert("Please enter a password with which to encrypt the message.");
        return null;
    }
    var prand = "";
    for (var I = 0; I < pwd.length; I++) {
        prand += pwd.charCodeAt(I).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));

    var incr = Math.ceil(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    if (mult < 2) {
        alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
        return null;
    }
    var salt = Math.round(Math.random() * 1000000000) % 100000000;
    prand += salt;
    while (prand.length > 10) {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for (var I = 0; I < str.length; I++) {
        enc_chr = parseInt(str.charCodeAt(I) ^ Math.floor((prand / modu) * 255));
        if (enc_chr < 16) {
            enc_str += "0" + enc_chr.toString(16);
        } else
            enc_str += enc_chr.toString(16);
        prand = (mult * prand + incr) % modu;
    }
    salt = salt.toString(16);
    while (salt.length < 8) salt = "0" + salt;
    enc_str += salt;
    return enc_str;
}

function Decrypt(str, pwd) {
    if (str == "") return "";
    if (!pwd || pwd == "") { var pwd = "1234"; }
    pwd = escape(pwd);
    if (str == null || str.length < 8) {
        alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
        return;
    }
    if (pwd == null || pwd.length <= 0) {
        alert("Please enter a password with which to decrypt the message.");
        return;
    }
    var prand = "";
    for (var I = 0; I < pwd.length; I++) {
        prand += pwd.charCodeAt(I).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos * 2) + prand.charAt(sPos * 3) + prand.charAt(sPos * 4) + prand.charAt(sPos * 5));
    var incr = Math.round(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    var salt = parseInt(str.substring(str.length - 8, str.length), 16);
    str = str.substring(0, str.length - 8);
    prand += salt;
    while (prand.length > 10) {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for (var I = 0; I < str.length; I += 2) {
        enc_chr = parseInt(parseInt(str.substring(I, I + 2), 16) ^ Math.floor((prand / modu) * 255));
        enc_str += String.fromCharCode(enc_chr);
        prand = (mult * prand + incr) % modu;
    }
    return unescape(enc_str);
}

$.extend({ getUrlVars: function () { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }, getUrlVar: function (name) { return $.getUrlVars()[name]; } });